import { callCloudFun } from "../utiles/callCloudFun";

const db = wx.cloud.database()
const _ = db.command
const employeesCollection = db.collection('employee')

/**
 * 获取员工列表
 * @param {Object} params - 查询参数
 * @param {string} params.keyword - 搜索关键词
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 */
export const getEmployees = async ({ keyword = '', page = 1, pageSize = 10 } : { keyword : string; page : number; pageSize : number }) => {
	try {
		let list : DB.IDocumentData[]
		if (keyword) {
			({ data: list } = await employeesCollection
				.where({
					$or: [
						{ name: db.RegExp({ regexp: keyword }) },
						{ username: db.RegExp({ regexp: keyword }) }
					]
				})
				.orderBy('createTime', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get())
		} else {
			({ data: list } = await employeesCollection
				.where({ username: _.exists(true) })
				.orderBy('createTime', 'desc')
				.skip((page - 1) * pageSize)
				.limit(pageSize)
				.get())
		}
		return list
	} catch (err) {
		console.error('获取员工列表失败:', err)
		wx.showToast({ title: err.message || '数据获取失败', icon: 'none' })
		throw err
	}
}

/**
 * 添加员工
 * @param {Object} employee - 员工数据
 */
export const addEmployee = async (employee : object) => {
	try {
		const res = await callCloudFun('employee', { addData: employee })
		return res
	} catch (err) {
		if ((err as any).errMsg && (err as any).errMsg.includes('username_ dup')) {
			wx.showToast({ title: '账号已存在', icon: 'none' })
		} else {
			wx.showToast({ title: err.message || '添加失败', icon: 'none' })
		}
		console.error('添加员工失败:', err)
		throw err
	}
}

/**
 * 更新员工信息
 * @param {string} id - 员工ID
 * @param {Object} data - 更新数据
 */
export const updateEmployee = async (params : any) => {
	const { id, ...data } = params
	data.updateTime = db.serverDate()
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		await employeesCollection.doc(id).update({ data })
		await wx.hideLoading()
	} catch (err) {
		await wx.hideLoading()
		wx.showToast({ title: err.message || '更新失败', icon: 'none' })
		throw err
	}
}

/**
 * 删除员工
 * @param {string} id - 员工ID
 */
export const deleteEmployee = async (id : string) => {
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		await employeesCollection.doc(id).remove()
		await wx.hideLoading()
	} catch (err) {
		await wx.hideLoading()
		wx.showToast({ title: err.message || '删除失败', icon: 'error' })
		console.error('切换状态失败:', err)
		throw err
	}
}